﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;

using Microsoft.Extensions.Configuration;

namespace Unity.Credentials
{
    public static class UnityCredentialsHelper
    {

        private static UnityServer CurrentServer =
            UnityServer.DEV;

        public static void SetCurrentEnvironment(UnityServer currentServer)
        {
            CurrentServer = currentServer;
        }

        public static Dictionary<object, object> GetDefaults()
        {
            return GetDefaults(CurrentServer);
        }

        private static Dictionary<object, object> LoadDefaultsConfigurationFromJsonFile(UnityServer server)
        {
            return LoadDefaultsConfigurationFromJsonFile($"default.{server.ToString().ToLower()}.json");
        }

        private static Dictionary<object, object> LoadDefaultsConfigurationFromJsonFile(string filename)
        {
            return LoadDefaultsConfigurationFromJsonFile(filename, Directory.GetCurrentDirectory());
        }

        private static Dictionary<object, object> LoadDefaultsConfigurationFromJsonFile(string filename, string baseDir)
        {
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
                .SetBasePath(baseDir)
                .AddJsonFile(filename);

            IConfigurationRoot configuration = configurationBuilder.Build();
            Dictionary<object, object> defaultProperties = new Dictionary<object, object>();
            if (configuration != null)
            {
                foreach (var item in configuration.GetChildren())
                {
                    defaultProperties.Add(item.Key, item.Value);
                }
            }
            return defaultProperties;
        }

        public static Dictionary<object, object> GetDefaults(UnityServer server)
        {
            try
            {
                Dictionary<object, object> properties = LoadDefaultsConfigurationFromJsonFile(server);
                return properties;
            }
            catch (Exception exception)
            {
                throw new UnityCredentialsException("Error get default credentials", exception);
            }
        }

        public static Dictionary<object, object> GetDefaults(UnityServer server, bool isDebug)
        {
            return null;
        }


        public static X509Certificate[] CreateCertificates(FileInfo cerificateFile)
        {
            List<X509Certificate> certificates = new List<X509Certificate>();
            return certificates.ToArray();
        }

    }
}
